package com.pms.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.entity.BaseGroupMember;
import com.pms.entity.BaseUser;
import com.pms.rpc.IKyOrganizationRPCService;
import com.pms.service.IBaseGroupMemberService;
import com.pms.service.IBaseUserService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pms.entity.CompanyCode;
import com.pms.mapper.CompanyCodeMapper;
import com.pms.service.ICompanyCodeService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 
 *
 * @author ljb
 * @email 517770986@qq.com
 * @date 2018-07-17 14:57:26
 */
@Service
public class CompanyCodeServiceImpl extends BaseServiceImpl<CompanyCodeMapper,CompanyCode> implements ICompanyCodeService {
    @Autowired
    public  CompanyCodeMapper companyCodeMapper;
    @Autowired
    IBaseUserService baseUserService;
    @Autowired
    IBaseGroupMemberService baseGroupMemberService;
    @Autowired
    IKyOrganizationRPCService kyOrganizationRPCService;
    @Override
    public String getInviteCode(Integer len) {
        String code = this.generateRandomStr(len);
        while (true) {
            CompanyCode member = companyCodeMapper.selectByCode(code);
            if (member == null) {
                break;
            }
            code = this.generateRandomStr(len);
        }
        return code;
    }


    public static String generateRandomStr(Integer len) {
        String generateSource = "0123456789";
        String rtnStr = "";
        for (int i = 0; i < len; i++) {
            String nowStr = String.valueOf(generateSource.charAt((int) Math.floor(Math.random() * generateSource.length())));
            rtnStr += nowStr;
            generateSource = generateSource.replaceAll(nowStr, "");
        }
        return rtnStr.toUpperCase();
    }

    /**
     *
     * @param entity
     * @param user
     * @param groupMember
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public  Boolean insert_user_groupMember(CompanyCode entity, BaseUser user, BaseGroupMember groupMember){
        kyOrganizationRPCService.addLoginLog(entity.getCompanyCode(),entity.getCompanyName());
        baseGroupMemberService.insert(groupMember);
        baseUserService.insert(user);
        companyCodeMapper.insert(entity);
        return true;
    }

    public Page<CompanyCode> selectBypageMap(Page<CompanyCode> page, Map<String,Object> map){
        int count=companyCodeMapper.countByPageList(map);
        List<CompanyCode> list= companyCodeMapper.selectBypageMap(map);
        page.setRecords(list);
        page.setTotal(count);
        return  page;
    }

}